package com.trace.trackshow;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Looper;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.leador.api.maps.MapController;
import com.leador.api.maps.model.CircleOptions;
import com.leador.api.maps.model.LatLng;
import com.leador.listener.OnGeoFenceListener;
import com.leador.module.request.Fence;
import com.leador.module.request.Historyalarm;
import com.leador.module.response.Result;
import com.leador.module.response.fence.HisAlarmResult;
import com.leador.module.response.fence.FenceCreateResult;

/**
 * Created by l on 2016/7/24.
 */
public class Geofence implements View.OnClickListener{
    // 地理围栏监听器
    protected static OnGeoFenceListener geoFenceListener = null;
    private Context mContext = null;
    // 围栏覆盖物
    protected static CircleOptions fenceOverlay = null;
    // 围栏半径
    protected static int radius = 100;

    protected static int radiusTemp = radius;

    public Geofence(Context context, LayoutInflater inflater) {
        initOnGeoFenceListener();
        mContext = context;
        mInflater = inflater;
        if (null == fenceOverlay) {
            queryFenceList();
        }
    }

    // 输入围栏信息对话框
    private void inputDialog() {
        final EditText circleRadius = new EditText(mContext);
        circleRadius.setFocusable(true);
        circleRadius.setText(radius + "");
        circleRadius.setInputType(InputType.TYPE_CLASS_NUMBER);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        builder.setTitle("围栏半径(单位:米)").setView(circleRadius)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        MainActivity.mapView.getMap().setOnMapClickListener(null);
                    }

                });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                String radiusStr = circleRadius.getText().toString();
                if (!TextUtils.isEmpty(radiusStr)) {
                    radiusTemp = radius;
                    radius = Integer.parseInt(radiusStr) > 0 ? Integer.parseInt(radiusStr) : radius;
                }
                Toast.makeText(mContext, "请点击地图标记围栏圆心", Toast.LENGTH_LONG).show();
            }
        });
        builder.show();
    }


    /**
     * 围栏列表
     */
    private void queryFenceList() {
        // 创建者（entity标识）
        String creator = MainActivity.entityName;
        // 围栏ID列表
        String fenceIds = "";
        MainActivity.client.getListFence(MainActivity.serviceId, creator, fenceIds, geoFenceListener);
    }

    /**
     * 初始化OnGeoFenceListener
     */
    private void initOnGeoFenceListener() {
        // 初始化geoFenceListener
        geoFenceListener = new OnGeoFenceListener() {
            @Override
            public void onRequestFailedCallback(Result result) {
                if(result == null){
                    return;
                }
                MainActivity.mapView.getMap().clear();
                if (null != fenceOverlayTemp) {
                    fenceOverlay = fenceOverlayTemp;
                    fenceOverlayTemp = null;
                }
                radius = radiusTemp;
                TrackUploadFragment.addMarker();
                showMessage("geoFence请求失败回调接口消息 : " + result.getMessage());
            }

            @Override
            public void onCreateCircularFenceCallback(FenceCreateResult result) {
                super.onCreateCircularFenceCallback(result);
                if(result == null){
                    return;
                }
                int status = Integer.valueOf(result.getStatus());
                if (0 == status) {
                    fenceId = Integer.valueOf(result.getFence_id());
                    fenceOverlayTemp = null;
                    showMessage("围栏创建成功");
                } else {
                    MainActivity.lMap.clear();
                    fenceOverlay = fenceOverlayTemp;
                    fenceOverlayTemp = null;
                    radius = radiusTemp;
                    TrackUploadFragment.addMarker();
                    showMessage("创建圆形围栏回调接口消息 : " + result.getMessage());
                }
            }

            @Override
            public void onUpdateFenceCallback(Result result) {
                super.onUpdateFenceCallback(result);
            }

            // 查询历史报警回调接口

            @Override
            public void onQueryHistoryAlarmCallback(HisAlarmResult alarmsResult) {
                super.onQueryHistoryAlarmCallback(alarmsResult);
                if(alarmsResult == null){
                    return;
                }
                showMessage(" 查询历史报警回调接口消息 : " + alarmsResult.getMessage());
            }


//            // 查询监控对象状态回调接口
//            @Override
//            public void onQueryMonitoredStatusCallback(String arg0) {
//                // TODO Auto-generated method stub
//                JSONObject dataJson = null;
//                try {
//                    dataJson = new JSONObject(arg0);
//                    int status = dataJson.getInt("status");
//                    if (0 == status) {
//                        int size = dataJson.getInt("size");
//                        if (size >= 1) {
//                            JSONArray jsonArray = dataJson.getJSONArray("monitored_person_statuses");
//                            JSONObject jsonObj = jsonArray.getJSONObject(0);
//                            String mPerson = jsonObj.getString("monitored_person");
//                            int mStatus = jsonObj.getInt("monitored_status");
//                            if (1 == mStatus) {
//                                showMessage("监控对象[ " + mPerson + " ]在围栏内");
//                            } else {
//                                showMessage("监控对象[ " + mPerson + " ]在围栏外");
//                            }
//                        }
//                    } else {
//                        showMessage("查询监控对象状态回调消息 : " + arg0);
//                    }
//                } catch (JSONException e) {
//                    // TODO Auto-generated catch block
//                    showMessage("解析查询监控对象状态回调消息失败");
//                }
//            }
        };
    }

    /**
     * 添加entity
     */
    protected static void addEntity() {
        int type = 0;
        MainActivity.client.setProtocolType(type);

        // entity标识
        String entityName = MainActivity.entityName;
        // 属性名称（格式 : "key1=value1,columnKey2=columnValue2......."）
        String columnKey = "";
//        MainActivity.client.addEntity(MainActivity.serviceId, entityName, columnKey, MainActivity.entityListener);
    }

    private LayoutInflater mInflater = null;
    protected PopupWindow popupwindow = null;
    private Button btnSetfence = null;
    private Button btnMonitoredstatus = null;
    private Button btnHistoryalarm = null;
    @SuppressLint({"InflateParams", "ClickableViewAccessibility"})
    protected void initPopupWindowView() {

        // 获取自定义布局文件menu_geofence.xml的视图
        View customView = mInflater.inflate(R.layout.menu_geofence, null);
        popupwindow = new PopupWindow(customView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 自定义view添加触摸事件
        customView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupwindow != null && popupwindow.isShowing()) {
                    popupwindow.dismiss();
                    popupwindow = null;
                }

                return false;
            }

        });

        btnSetfence = (Button) customView.findViewById(R.id.btn_setFence);
        btnMonitoredstatus = (Button) customView.findViewById(R.id.btn_monitoredStatus);
        btnHistoryalarm = (Button) customView.findViewById(R.id.btn_historyAlarm);

        btnSetfence.setOnClickListener(this);
        btnMonitoredstatus.setOnClickListener(this);
        btnHistoryalarm.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // 设置围栏
        switch (v.getId()) {
            // 设置围栏
            case R.id.btn_setFence:
                inputDialog();
                MainActivity.mapView.getMap().setOnMapClickListener(mapClickListener);
                popupwindow.dismiss();
                break;

            // 历史报警
            case R.id.btn_historyAlarm:
                historyAlarm();
                popupwindow.dismiss();
                break;

            // 监控对象状态
            case R.id.btn_monitoredStatus:
                monitoredStatus();
                popupwindow.dismiss();
                break;

            default:
                break;
        }
    }

    protected static CircleOptions fenceOverlayTemp = null;
    // 围栏圆心纬度
    private double latitude = 0;

    // 围栏圆心经度
    private double longitude = 0;
    protected MapController.OnMapClickListener mapClickListener = new MapController.OnMapClickListener() {

        public void onMapClick(LatLng arg0) {
            // TODO Auto-generated method stub
            MainActivity.mapView.getMap().clear();
            latitude = arg0.latitude;
            longitude = arg0.longitude;

            fenceOverlayTemp = fenceOverlay;
            fenceOverlay = new CircleOptions().fillColor(0x000000FF).center(arg0)
                    .strokeColor (Color.rgb(0xff, 0x00, 0x33)).radius(radius);

            TrackUploadFragment.addMarker();
            createOrUpdateDialog();
        }

    };

    // 围栏编号
    protected static int fenceId = 0;
    /**
     * 设置围栏对话框
     */
    private void createOrUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        builder.setTitle("确定设置围栏?");

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                MainActivity.mapView.getMap().clear();
                // 添加覆盖物
                if (null != fenceOverlayTemp) {
                    fenceOverlay = fenceOverlayTemp;
                }
                radius = radiusTemp;
                TrackUploadFragment.addMarker();
                MainActivity.mapView.getMap().setOnMapClickListener(null);
            }
        });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

                if (0 == fenceId) {
                    // 创建围栏
                    createFence();
                    } else {
                    // 更新围栏
                    updateFence();
                    }
                MainActivity.mapView.getMap().setOnMapClickListener(null);
            }
        });
        builder.show();
    }

    private void showMessage(String message) {
        Looper.prepare();
        Toast.makeText(MainActivity.mContext, message, Toast.LENGTH_LONG).show();
        Looper.loop();
    }

    /**
     * 创建围栏（若创建围栏时，还未创建entity标识，请先使用addEntity(...)添加entity）
     */
    private void createFence() {
        Fence fence = new Fence();
        fence.setServiceId(MainActivity.serviceId);
        fence.setFenceName(MainActivity.entityName+"_fence");
        fence.setFenceDesc("test");
        fence.setCreator(MainActivity.entityName);
        fence.setMonitoredPersons(MainActivity.entityName);
        fence.setValidTimes("0800,2300");
        fence.setValidCycle(4);
        fence.setValidDate("");
        fence.setValidDays("");
        fence.setShape(1);
        fence.setCoordType(3);
        fence.setCenter(longitude + "," + latitude);
        fence.setRadius(Geofence.radius);
        fence.setCoordStr("");
        fence.setAlarmCondition(3);
        MainActivity.client.createFence(fence,
                geoFenceListener);
    }

    /**
     * 更新围栏
     */
    private void updateFence(){
        Fence fence = new Fence();
        fence.setServiceId(MainActivity.serviceId);
        fence.setFenceName(MainActivity.entityName+"_fence");
        fence.setFenceDesc("test");
        fence.setCreator(MainActivity.entityName);
        fence.setMonitoredPersons(MainActivity.entityName);
        fence.setValidTimes("0800,2300");
        fence.setValidCycle(4);
        fence.setValidDate("");
        fence.setValidDays("");
        fence.setShape(1);
        fence.setCoordType(3);
        fence.setCenter(longitude + "," + latitude);
        fence.setRadius(Geofence.radius);
        fence.setCoordStr("");
        fence.setAlarmCondition(3);
        //and create diff
        fence.setObservers("");
        fence.setFenceId(fenceId);
        MainActivity.client.updateFence(fence,
                geoFenceListener);
    }

    /**
     * 报警信息
     */
    private void historyAlarm() {
        Historyalarm historyalarm = new Historyalarm();
        historyalarm.setServiceId(MainActivity.serviceId);
        // 围栏ID
        int fenceId = Geofence.fenceId;
        historyalarm.setFenceId(fenceId);
        // 监控对象列表（多个entityName，以英文逗号"," 分割）
        String monitoredPersons = MainActivity.entityName;
        historyalarm.setMonitored_persons(monitoredPersons);
        // 开始时间（unix时间戳）
        int beginTime = (int) (System.currentTimeMillis() / 1000 - 12 * 60 * 60);
        historyalarm.setBeginTime(Long.valueOf(beginTime));
        // 结束时间（unix时间戳）
        int endTime = (int) (System.currentTimeMillis() / 1000);
        historyalarm.setEndTime(endTime);

        historyalarm.setPageNum(1);
        MainActivity.client.queryFenceHistoryAlarmInfo(historyalarm,
                geoFenceListener);
    }


    /**
     * 监控状态
     */
    private void monitoredStatus() {

        // 围栏ID
        int fenceId = Geofence.fenceId;
        // 监控对象列表（多个entityName，以英文逗号"," 分割）
        Log.e("fenceId is",fenceId+"");
        String monitoredPersons = MainActivity.entityName;
        MainActivity.client.queryMonitoredStatus(MainActivity.serviceId, fenceId, monitoredPersons,
                geoFenceListener);
    }



}
